$(function(){

    if(!window.base.getLocalStorage('token')){
        window.location.href = 'login.html';
    }


    const RECYCLE = 'recycleOrder';
    const BUY = 'buyOrder';

    // recycle
    const UNDELIVERY = 1;
    const DELIVERED = 3;
    const PAID = 2;




    var pageIndex=1,
        currentOrder = BUY,
        moreDataFlag=true;
    getOrders(pageIndex);
    /*
    * 获取数据 分页
    * params:
    * pageIndex - {int} 分页下表  1开始
    */

    function getOrders(pageIndex){
        var params={
            url:'order/paginate',
            data:{page:pageIndex, size:20, type: currentOrder},
            tokenFlag:true,
            sCallback:function(res) {
                var str = getOrderHtmlStr(res);
                $('#order-table').append(str);
            }
        };
        window.base.getData(params);
    }

    /*拼接html字符串*/
    function getOrderHtmlStr(res){
        // res.data = []
        // res.data.data = need
        var data = res.data.data;
        console.log(data);
        if (data){
            var len = data.length,
                str = '', 
                item;
            for (var i = 0; i < len; i++) {
                item = data[i];
                str += '<tr>' +
                    '<td>' + item.order_no + '</td>' +
                    '<td>' + getOrderItems(item.snap_items) + '</td>' +
                    '<td>￥' + item.total_price + '</td>' +
                    '<td>' + getOrderAddress(item.snap_address) + '</td>' +
                    '<td>' + getOrderStatus(item.status) + '</td>' +
                    '<td>' + item.create_time + '</td>' +
                    '<td data-id="' + item.id + '">' + getBtns(item.status) + '</td>' +
                    '</tr>';
            }
        } else{
            ctrlLoadMoreBtn();
            moreDataFlag=false;
        }

        return str;
    }

    function getOrderItems(arr) {
        var str = '';
        for(var i = 0; i<arr.length; i++){
            str += '<span>'+ arr[i].name +  '&nbsp;&nbsp;*&nbsp;&nbsp;' +arr[i].count+'</span><br>';
        }
        return str;
    }

    function getOrderAddress(address) {
        return '<span>' + address.name + '&nbsp;&nbsp;' +'<i>'+ address.mobile + '</i><br>' +
          address.province + address.city + address.country + '<br>' + address.detail + '</span>';
    }

    /*根据订单状态获得标志*/
    function getOrderStatus(status){
        var arr=[{
            cName:'unpay',
            txt:'未付款'
        },{
            cName:'payed',
            txt:'已付款'
        },{
            cName:'done',
            txt:'已发货'
        },{
            cName:'unstock',
            txt:'缺货'
        },{
            cName:'undelievery',
            txt:'未发货'
        }];
        if(currentOrder == BUY) {
            return '<span class="order-status-txt ' + arr[status - 1].cName + '">' + arr[status - 1].txt + '</span>';
        }
        else {

            var index = 0;
            // recycle
            // const UNDELIVERY = 1;
            // const DELIVERED = 3;
            // const PAID = 2;
            if(status == UNDELIVERY){
                index = 4;
            }
            if(status == DELIVERED){
                index = 2;
            }
            if(status == PAID){
                index = 1;
            }
            return '<span class="order-status-txt ' + arr[index].cName + '">' + arr[index].txt + '</span>';
        }
    }

    /*根据订单状态获得 操作按钮*/
    function getBtns(status){
        var arr=[{
            cName:'done',
            txt:'发货'
        },{
            cName:'unstock',
            txt:'缺货'
        },{
            cName:'pay',
            txt:'转帐'
        }];
        var index;
        if(currentOrder == BUY){
            if(status==2 || status==4){
                index=0;
                if(status==4){
                    index=1;
                }
                return '<span class="order-btn '+arr[index].cName+'">'+arr[index].txt+'</span>';
            }else{
                return '';
            }
        }

        if(currentOrder == RECYCLE){
            if(status==3){
                index=2;
                return '<span class="order-btn '+arr[index].cName+'">'+arr[index].txt+'</span>';
            }else{
                return '';
            }
        }
    }



        /*加载recycle*/
    $(document).on('click','.recycle',function(){
        $('.recycle').addClass("clicked");
        $('.buy').removeClass("clicked");
        $('#order-table').empty(); 
        $('.load-more').show().next().hide()
        currentOrder = RECYCLE;
        pageIndex = 1;
        moreDataFlag = true;
        getOrders(pageIndex);
    });

    /*加载buy*/
    $(document).on('click','.buy',function(){
        $('.buy').addClass("clicked");
        $('.recycle').removeClass("clicked");
        $('#order-table').empty(); 
        $('.load-more').show().next().hide()
        currentOrder = BUY;
        pageIndex = 1;
        moreDataFlag = true;
        getOrders(pageIndex);
    });


    /*控制加载更多按钮的显示*/
    function ctrlLoadMoreBtn(){
        if(moreDataFlag) {
            $('.load-more').hide().next().show();
        }
    }

    /*加载更多*/
    $(document).on('click','.load-more',function(){
        if(moreDataFlag) {
            pageIndex++;
            getOrders(pageIndex);
        }
    });

    /*发货*/
    $(document).on('click','.order-btn.done',function(){
        var $this=$(this),
            $td=$this.closest('td'),
            $tr=$this.closest('tr'),
            id=$td.attr('data-id'),
            $tips=$('.global-tips'),
            $p=$tips.find('p');
        var params={
            url:'express/buy',
            type:'post',
            data:{
                order_id: id,
                comp_name: '顺风',
                express_no: '123456fromCMS',
            },
            tokenFlag:true,
            sCallback:function(res) {
                console.log(res);
                if(res.info=='ok'){
                   $tr.find('.order-status-txt')
                       .removeClass('pay').addClass('done')
                       .text('已发货');
                    $this.remove();
                    $p.text('操作成功');
                }else{
                    $p.text('操作失败');
                }
                $tips.show().delay(1500).hide(0);
            },
            eCallback:function(res){
                console.log(res);
                $p.text('操作失败');
                $tips.show().delay(1500).hide(0);
            }
        };
        window.base.getData(params);
    });

    /*转账*/
    $(document).on('click','.order-btn.pay',function(){
        var $this=$(this),
            $td=$this.closest('td'),
            $tr=$this.closest('tr'),
            id=$td.attr('data-id'),
            $tips=$('.global-tips'),
            $p=$tips.find('p');
        var params={
            url:'pay/recycle?id='+ id + '&XDEBUG_SESSION_START=14187',
            type:'post',
            // data:{id:id},
            tokenFlag:true,
            sCallback:function(res) {
                console.log(res);
                if(res.info=='ok'){
                    $tr.find('.order-status-txt')
                        .removeClass('done').addClass('payed')
                        .text('已付款');
                    $this.remove();
                    $p.text('操作成功');
                }else{
                    $p.text('操作失败');
                }
                $tips.show().delay(1500).hide(0);
            },
            eCallback:function(res){
                console.log(res);
                $p.text('操作失败');
                $tips.show().delay(1500).hide(0);
            }
        };
        window.base.getData(params);
    });

    /*退出*/
    $(document).on('click','#login-out',function(){
        window.base.deleteLocalStorage('token');
        window.location.href = 'login.html';
    });
});